package com.yuanduo_app.bridge

import android.text.TextUtils
import android.util.Log
import android.webkit.MimeTypeMap
import com.facebook.react.bridge.Callback
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactMethod
import com.google.gson.Gson
import com.xujl.fastlib.base.BaseModule
import com.xujl.fastlib.http.NetworkManager
import com.xujl.fastlib.utils.JsonUtil
import com.xujl.fastlib.utils.LogS
import com.xujl.fastlib.utils.StringUtils
import com.yuanduo_app.consts.RNEvent
import com.yuanduo_app.db.waterdb.WaterData
import com.yuanduo_app.db.waterdb.WaterUtils
import com.yuanduo_app.db.waterdb.waterDB
import com.yuanduo_app.event.CheckVersionEvent
import com.yuanduo_app.event.ChooseImageEvent
import com.yuanduo_app.utils.JsonUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import java.util.*

class DataModule(reactContext: ReactApplicationContext?) : BaseModule(reactContext) {
    var callback: Callback? = null
        private set

    override fun getName(): String {
        return "DataModule"
    }

    /**
     * 保存用户登录信息
     *
     * @param json
     */
    @ReactMethod
    fun saveUserAccout(json: String?) {
    }

    @ReactMethod
    fun checkVersion(isLoading: String) {
        LogS.i(TAG, "checkVersion:$isLoading")
        EventBus.getDefault()
            .post(CheckVersionEvent(!StringUtils.equals(isLoading, "initlization")))
    }

    /**
     * 获取通用数据
     *
     * @param key
     * @param callback
     */
    @ReactMethod
    fun getCommonData(key: String, callback: Callback?) {
        if (StringUtils.isEmpty(key) || callback == null) {
            return
        }
        if (StringUtils.startWith(key, TYPE_CONFIG)) {
            getConfigData(key, callback)
        } else {
        }
    }

    @ReactMethod
    fun getFileType(path: String?, callback: Callback) {
        val extension = MimeTypeMap.getFileExtensionFromUrl(path)
        if (!TextUtils.isEmpty(extension)) {
            //使用系统API，获取MimeTypeMap的单例实例，然后调用其内部方法获取文件后缀名（扩展名）所对应的MIME类型
            callback.invoke(
                MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase())!!
                    .replace("video/", "")
            )
        }
    }

    @ReactMethod
    fun chooseImage(callback: Callback?) {
        this.callback = callback
        EventBus.getDefault().post(ChooseImageEvent(""))
    }

    @ReactMethod
    fun chooseImageOrVideo(callback: Callback?) {
        this.callback = callback
        EventBus.getDefault().post(ChooseImageEvent("video"))
    }

    @ReactMethod
    fun chooseFaceImage(callback: Callback?) {
        this.callback = callback
        EventBus.getDefault().post(ChooseImageEvent("faceCer"))
    }

    private fun getConfigData(key: String, callback: Callback) {
        when (key) {
            DATA_HOST -> {
                val map: MutableMap<String, String> = HashMap(1)
                map["host"] = NetworkManager.getInstance().url
                callback.invoke(Gson().toJson(map))
            }
            else -> {
            }
        }
    }

    /**
     * 获取所有水印相机拍照内容
     */
    @ReactMethod
    fun getAllWater(callback: Callback?) {
        GlobalScope.launch(Dispatchers.Main) {
            var data = withContext(Dispatchers.IO) {
                waterDB.waterDao().getAll()
            }
            callback?.invoke(Gson().toJson(data))
        }
    }

    @ReactMethod
    fun saveWaterInfo(json: String?) {
        json?.let {
            var info = JsonUtil.fromJson(json, WaterData::class.java)
            if (info.imageId > 0) { //新数据才进行存储
                return
            }
            GlobalScope.launch {
                withContext(Dispatchers.IO) {
                    waterDB.waterDao().insertWater(info)
                }
                Log.i(TAG, "saveWaterInfo:launch ")
            }
            Log.i(TAG, "saveWaterInfo: ")
        }
    }


    /**
     * 上传成功
     */
    @ReactMethod
    fun uploadWaterSuccess(imageJson: String) {
        GlobalScope.launch {
            var uploadlist = JsonUtils.jsonToArrayList(imageJson, WaterData::class.java)
            withContext(Dispatchers.IO) {
                uploadlist.forEach {
                    waterDB.waterDao().deleteWater(it)
                }
            }
            WaterUtils.checkWaterData()
        }
    }


    companion object {
        private const val TAG = "DataModule"
        private const val TYPE_CONFIG = "config_"
        private const val DATA_HOST = TYPE_CONFIG + "host"
        const val MAP_POSITION = "map_position"
        const val ON_SCAN_FINISH_BLOCK = "onScanFinishBlock"
    }
}